package com.kos.backend.consumer;

import com.alibaba.fastjson2.JSONObject;
import com.kos.backend.consumer.utils.Game;
import com.kos.backend.consumer.utils.JwtAuthentication;
import com.kos.backend.mapper.RecordMapper;
import com.kos.backend.mapper.SnakeMapper;
import com.kos.backend.mapper.UserMapper;
import com.kos.backend.pojo.Snake;
import com.kos.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
//不能以'/'结尾
@ServerEndpoint("/websocket/{token}")
public class WebSocketServer {

    //对所有实例都可见
    public static final ConcurrentHashMap<Integer,WebSocketServer> users = new ConcurrentHashMap<>();

    private User user;
    private Session session = null;

    public static UserMapper userMapper;
    public static RecordMapper recordMapper;

    private static SnakeMapper snakeMapper;

    public static RestTemplate restTemplate;

    public Game game;

    private final static String addPlayerUrl = "http://127.0.0.1:8091/player/add";
    private final static String removePlayerUrl = "http://127.0.0.1:8091/player/remove";


    @Autowired
    public void setUserMapper(UserMapper userMapper){
        WebSocketServer.userMapper = userMapper;
    }
    @Autowired
    public void setRecordMapper(RecordMapper recordMapper){
        WebSocketServer.recordMapper = recordMapper;
    }
    @Autowired
    public void setSnakeMapper(SnakeMapper snakeMapper){
        WebSocketServer.snakeMapper = snakeMapper;
    }
    @Autowired
    public void setRestTemplate(RestTemplate restTemplate){
        WebSocketServer.restTemplate = restTemplate;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        // 建立连接

        this.session = session;
        System.out.println("connected");
        Integer userId = JwtAuthentication.getUserId(token);
        user = userMapper.selectById(userId);

        if(this.user != null) {
            users.put(userId,this);
         } else {
            this.session.close();
        }
        System.out.println(users);
    }

    @OnClose
    public void onClose() {
        // 关闭链接
        System.out.println("disconnected");
        if(this.user != null){
            users.remove(this.user.getId());

        }
    }

    //
    public static void startGame(Integer aId, Integer asnakeId, Integer bId, Integer bsnakeId){
        User a = userMapper.selectById(aId);
        User b = userMapper.selectById(bId);
        Snake snakeA = snakeMapper.selectById(asnakeId);
        Snake snakeB = snakeMapper.selectById(bsnakeId);
        Game game = new Game(13,14,20,a.getId(),snakeA,b.getId(),snakeB);
        game.creatMap();
        if(users.get(a.getId()) != null){
            users.get(a.getId()).game = game;
        }
        if(users.get(b.getId()) != null){
            users.get(b.getId()).game = game;
        }


        game.start();

        JSONObject respGame = new JSONObject();
        respGame.put("a_id",game.getPlayerA().getId());
        respGame.put("a_sx",game.getPlayerA().getId());
        respGame.put("a_sy",game.getPlayerA().getId());
        respGame.put("b_id",game.getPlayerB().getId());
        respGame.put("b_sx",game.getPlayerB().getId());
        respGame.put("b_sy",game.getPlayerB().getId());
        respGame.put("map",game.getG());

        JSONObject respA = new JSONObject();
        respA.put("event","start_matching");
        respA.put("opponent_username",b.getUsername());
        respA.put("opponent_photo",b.getPhoto());
        respA.put("game",respGame);
        if(users.get(a.getId()) != null){
            users.get(a.getId()).sendMessage(respA.toJSONString());
        }


        JSONObject respB = new JSONObject();
        respB.put("event","start_matching");
        respB.put("opponent_username",a.getUsername());
        respB.put("opponent_photo",a.getPhoto());
        respB.put("game",respGame);
        if(users.get(b.getId()) != null){
            users.get(b.getId()).sendMessage(respB.toJSONString());
        }
    }

    private void move(int direction){
        if(game.getPlayerA().getId().equals(user.getId())){
            //本人操作
            if(game.getPlayerA().getSnakeId().equals(-1)){
                game.setNextStepA(direction);
            }
        } else if(game.getPlayerB().getId().equals(user.getId())){
            if(game.getPlayerB().getSnakeId().equals(-1)){
                game.setNextStepB(direction);
            }
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {            //当作路由
        // 从Client接收消息,服务器接收用户信息
        System.out.println("receive message");
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
        if("start_matching".equals(event)){
            startMatching(data.getInteger("snake_id"));
        } else if("stop_matching".equals(event)){
            stopMatching();
        } else if("move".equals(event)){
            move(data.getInteger("direction"));
        }
    }

    public void startMatching(Integer snakeId){
        System.out.println("start matching");
        MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
        data.add("user_id",this.user.getId().toString());
        data.add("rating",this.user.getRating().toString());
        data.add("snake_id",snakeId.toString());
        restTemplate.postForObject(addPlayerUrl,data,String.class);

    }

    public void stopMatching(){
        System.out.println("stop matching");
        MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
        data.add("user_id",this.user.getId().toString());
        System.out.println(data);
        restTemplate.postForObject(removePlayerUrl,data,String.class);
    }


    public void sendMessage(String message) {
        synchronized (this.session) {
            try{
                this.session.getBasicRemote().sendText(message);
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
}